package com.rtsapp.server.platform;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rtsapp.server.app.AppConfig;
import com.rtsapp.server.utils.StringUtils;
import org.apache.commons.codec.binary.Hex;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import com.rtsapp.server.logger.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.MessageDigest;

/**
 * Created by admin on 16-2-24.
 */
public class XYLoginService implements IPlatformLoginService {

    private static final Logger LOGGER = com.rtsapp.server.logger.LoggerFactory.getLogger( XYLoginService.class );

    //    http://passport.xyzs.com/checkLogin.php
    private static final String url = AppConfig.getInstance().getXYUrl();
    //    100027876
    private static final String appId = AppConfig.getInstance().getXYAppId();
    //    iLwYmZlZ9DFA9wVwyAIr4rYXuWKmMca8
    private static final String appKey = AppConfig.getInstance().getXYAppKey();
    //    jEzlQEcsqZdqr6N3Ub5knF1Rozr7wFH8
    private static final String payKey = AppConfig.getInstance().getXYPayKey();

    //登陆成功
    private static final int CODE_LOGIN_SUCCESS = 0;
    //uid为空
    private static final int CODE_LOGIN_UID_NULL = 2;
    //appid为null
    private static final int CODE_LOGIN_APPID_NULL = 20;
    //token超时
    private static final int CODE_LOGIN_TOKEN_TIMEOUT = 997;
    //验证失败
    private static final int CODE_LOGIN_VERIFY_FAIL = 999;


    @Override
    public String validateLoginToken(  String token, String uid  ){

        try {

            String json = checkSession( token, appId, uid );

            if( ! StringUtils.isEmpty(json) ){

                JSONObject jsonObject =  JSON.parseObject(json);
                int ret =  jsonObject.getIntValue("ret");

                if( ret == CODE_LOGIN_SUCCESS ) {

                    LOGGER.debug("pp助手:有效用户:userid=" + uid );
                    return "xy_" + uid;
                }

            }
        } catch (IOException e) {
            LOGGER.error( "XY用户验证调用异常", e );
            return null;
        }

        LOGGER.debug("XY:用户验证失败" );
        return null;
    }


    /**
     * 验证session
     * @param token
     * @param appId
     * @param uid
     * @return
     * @throws IOException
     */
    public static String checkSession( String token, String appId, String uid ) throws IOException
    {
        if (null == token || null == appId || null == uid)
        {
            return null;
        }

        String content = "appid="+appId+"&token="+token+"&uid="+uid;


        return httpPostJson(url,  content );
    }

    /**
     * http post json string
     * @param url
     * @param content
     * @return
     * @throws IOException
     */
    public static String httpPostJson(String url, String content) throws IOException
    {
        if (null == url || url.isEmpty() || null == content || content.isEmpty())
        {
            return "";
        }
        // 请求地址
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
        // 设置超时时间为3s
        RequestConfig config = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).setAuthenticationEnabled(false).build();
        httpPost.setConfig(config);

        // 设置参数
        StringEntity se = new StringEntity(content);
        httpPost.setEntity(se);

        // 准备环境
        try (CloseableHttpClient http = HttpClients.createDefault(); CloseableHttpResponse response = http.execute(httpPost);)
        {
            // 返回内容
            HttpEntity entity = response.getEntity();
            // 主体数据
            InputStream in = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            // 读取
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null)
            {
                sb.append(line);
            }
            return sb.toString();
        }
    }

    /**
     * MD5加密
     * @param s
     *        被加密的字符串
     * @return 加密后的字符串
     */
    public static String md5(String s)
    {
        if (s == null) s = "";
        try
        {
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(s.getBytes("UTF-8"));
            return new String(Hex.encodeHex(mdTemp.digest()));
        }
        catch (Exception e)
        {
            throw new RuntimeException(e);
        }
    }

}